<template>
    <div class="login-container">
        <el-card class="box-card">
            <div class="login-body">
                <div class="login-title" @click="toIndex">
                    <img src="../../assets/lyh.png" class="login-logo" />
                    <span class="login-title-text">用户登录</span>
                </div>
                <el-form ref="form" :model="userForm">
                    <el-input
                        placeholder="请输入账号"
                        v-model="userForm.accountNumber"
                        class="login-input"
                        clearable
                    >
                        <template #prepend>
                            <i class="el-icon-user-solid"></i>
                        </template>
                    </el-input>
                    <el-input
                        placeholder="请输入密码"
                        v-model="userForm.userPassword"
                        class="login-input"
                        show-password
                        @keyup.enter.native="login"
                        clearable
                    >
                        <template #prepend>
                            <i class="el-icon-lock"></i>
                        </template>
                    </el-input>
                    <div class="login-submit">
                        <el-button type="primary" size="large" round @click="login">登录</el-button>
                        <el-button type="warning" size="large" round @click="$router.push('/sign-in')">注册</el-button>
                        <el-button type="success" size="large" round @click="$router.push('/login-admin')">管理员登录</el-button>
                    </div>
                    <div class="login-thirdplatform">
                        <el-tooltip content="Gitee 登录" placement="top">
                            <img src="../../assets/gitee.png" alt="Gitee 登录" class="gitee-login" @click="render" />
                        </el-tooltip>
                    </div>
                    <!-- 在登录表单最后添加找回密码链接 -->
                    <div class="forgot-password">
                        <el-link type="primary" @click="showForgotDialog">忘记密码？</el-link>
                    </div>
                </el-form>
            </div>
        </el-card>

        <!-- 将对话框移到el-card外部，确保ref能正确绑定 -->
        <el-dialog 
    title="找回密码" 
    :visible.sync="forgotDialogVisible" 
    width="30%" 
    ref="forgotDialogRef"
    @open="initForgotForm">
    <el-form 
        :model="forgotForm" 
        :rules="forgotRules" 
        ref="forgotFormRef"
        :key="forgotFormKey">
        <!-- 邮箱输入 -->
        <el-form-item prop="email">
            <el-input v-model="forgotForm.email" placeholder="请输入注册邮箱">
                <template slot="prepend">
                    <i class="el-icon-message"></i>
                </template>
            </el-input>
        </el-form-item>

        <!-- 验证码 -->
        <el-form-item prop="code">
            <el-input v-model="forgotForm.code" placeholder="请输入验证码">
                <template slot="prepend">
                    <i class="el-icon-key"></i>
                </template>
                <template slot="append">
                    <el-button 
                        @click="sendResetCode" 
                        :disabled="codeSending"
                        :loading="codeSending">
                        {{ codeSending ? `${countdown}s后重试` : '获取验证码' }}
                    </el-button>
                </template>
            </el-input>
        </el-form-item>

        <!-- 新密码 -->
        <el-form-item prop="newPassword">
            <el-input 
                v-model="forgotForm.newPassword" 
                placeholder="请输入新密码"
                show-password>
                <template slot="prepend">
                    <i class="el-icon-lock"></i>
                </template>
            </el-input>
        </el-form-item>
    </el-form>

    <template #footer>
        <el-button @click="closeForgotDialog">取消</el-button>
        <el-button type="primary" @click="resetPassword">确认重置</el-button>
    </template>
</el-dialog>
    </div>
</template>

<script>
import api from "../../utils/request";
export default {
    name: "login",
    data() {
        return {
            userForm: {
                accountNumber: '',
                userPassword: ''
            },
            forgotDialogVisible: false,
            forgotFormKey: 0,  // 用于强制重新渲染表单
            forgotForm: {
                email: '',
                code: '',
                newPassword: ''
            },

            forgotRules: {
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }
                ],
                code: [
                    { required: true, message: '请输入验证码', trigger: 'blur' },
                    { pattern: /^\d{6}$/, message: '验证码为6位数字', trigger: 'blur' }
                ],
                newPassword: [
                   { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 8, message: '密码长度至少8位', trigger: 'blur' },
                    {
                        pattern: /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*(),.?":{}|<>]).{8,}$/,
                        message: '密码至少包含字母、数字和特殊字符',
                        trigger: 'blur'
                    }
                ]
            },
            codeSending: false,
            countdown: 60
        };
    },
    methods: {
        render() {
            window.location.href = `http://localhost:8080/user/render`;
        },
        login() {
            this.$api.userLogin(this.userForm).then(res => {
                if (res.status_code === 1) {
                    console.log("登录成功！");
                    this.$globalData.userInfo = res.data.user;
                    localStorage.setItem("token", res.data.token);
                    this.$api.getUserInfo().then(res => {
                        console.log("Login的UserInfo为:", res.data.user);
                    });
                    this.$router.replace({ path: '/index' });
                } else {
                    console.log("账号或密码错误，请重试!");
                    this.$message.error(res.msg);
                }
            }).catch(error => {
                if (error.response.data.status_code === 40303) {
                    this.$message.error("该账户已违规！");
                } else {
                    this.$message.error("登录失败，请检查账号和密码！");
                }
                console.error("登录请求错误:", error);
            });
        },
        // 初始化忘记密码表单
        initForgotForm() {
            // 重置表单数据
            this.forgotForm = {
                email: '',
                code: '',
                newPassword: ''
            };

            // 强制重新渲染表单
            this.forgotFormKey++;

            // 使用 $nextTick 确保 DOM 更新后执行
            this.$nextTick(() => {
                if (this.$refs.forgotFormRef) {
                    this.$refs.forgotFormRef.resetFields();
                    console.log('Forgot password form initialized successfully');
                } else {
                    console.error('Forgot password form ref not found');
                }
            });
        },
        // 显示找回密码对话框
        showForgotDialog() {
            // 显示对话框
            this.forgotDialogVisible = true;
            console.log('Forgot password dialog opened');
        },
        // 关闭找回密码对话框
        closeForgotDialog() {
            this.forgotDialogVisible = false;
            console.log('Forgot password dialog closed');
        },
        
        // 发送重置密码验证码
        async sendResetCode() {
            try {
                await this.$refs.forgotFormRef.validateField('email');
                this.codeSending = true;
                
                const res = await this.$api.sendCode({
                    email: this.forgotForm.email,
                    type: 'RESET_PWD'
                });
                
                if (res.status_code === 1) {
                    this.$message.success('验证码已发送');
                    this.startCountdown();
                }
            } catch (error) {
                this.codeSending = false;
                this.$message.error(error.response.data.msg || '发送失败');
            }
        },
        
        // 倒计时方法
        startCountdown() {
            this.countdown = 60;
            const timer = setInterval(() => {
                if (this.countdown <= 0) {
                    clearInterval(timer);
                    this.codeSending = false;
                    return;
                }
                this.countdown--;
            }, 1000);
        },
        
        // 重置密码
        async resetPassword() {
            try {
                await this.$refs.forgotFormRef.validate();
                
                const res = await this.$api.resetPassword({
                    email: this.forgotForm.email,
                    code: this.forgotForm.code,
                    newPassword: this.forgotForm.newPassword
                });
                
                if (res.status_code === 1) {
                    this.$message.success('密码重置成功');
                    this.forgotDialogVisible = false;
                }
            } catch (error) {
                this.$message.error(error.response.data.msg || '重置失败');
            }
        },
        toIndex() {
            this.$router.replace({ path: '/index' });
        }
    }
};
</script>

<style scoped>
/* 新增找回密码链接样式 */
.forgot-password {
    margin-top: 15px;
    text-align: right;
}
.forgot-password .el-link {
  font-size: 14px;
  color: #409eff;
  text-decoration: none;
}
.forgot-password .el-link:hover {
  color: #66b1ff;
  text-decoration: underline;
}
/* 背景容器：深色渐变背景，加入动态 overlay 效果 */
.login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    width: 100%;
    background: linear-gradient(135deg, #0f2027, #203a43, #2c5364);
    background-size: cover;
    overflow: hidden;
    position: relative;
}

.login-container::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: url('../../assets/Background_2.png') center/cover no-repeat;
    opacity: 0.08;
}

/* 卡片采用玻璃效果：半透明背景 + 模糊背景 */
.box-card {
    width: 400px;
    border-radius: 15px;
    backdrop-filter: blur(15px);
    background: rgba(255, 255, 255, 0.2);
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
    border: 1px solid rgba(255, 255, 255, 0.3);
    overflow: hidden;
}

/* 登录主体区域 */
.login-body {
    padding: 40px 30px;
    display: flex;
    flex-direction: column;
    align-items: center;
}

/* 标题：添加悬停动画 */
.login-title {
    margin-bottom: 30px;
    text-align: center;
    cursor: pointer;
    display: flex;
    align-items: center;
    transition: transform 0.3s;
}
.login-title:hover {
    transform: scale(1.05);
}
.login-logo {
    width: 50px;
    margin-right: 10px;
    filter: drop-shadow(0 0 8px rgba(0, 0, 0, 0.3));
}
.login-title-text {
    color: #f0f0f0;
    font-size: 28px;
    font-weight: 700;
    letter-spacing: 1px;
}

/* 输入框样式：圆角、背景半透明并有悬停阴影 */
.login-input {
    margin-bottom: 20px;
    border-radius: 10px;
}
.el-input__inner {
    height: 45px;
    border-radius: 10px;
    background-color: rgba(255, 255, 255, 0.85);
    color: #333;
    font-size: 16px;
    transition: box-shadow 0.3s;
}
.el-input__inner:hover,
.el-input__inner:focus {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25);
}

/* 按钮组：响应式布局与动画效果 */
.login-submit {
    margin-top: 20px;
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    justify-content: center;
}
.el-button {
    min-width: 120px;
    font-weight: 600;
    font-size: 16px;
    transition: transform 0.3s, box-shadow 0.3s;
}
.el-button:hover {
    transform: translateY(-3px);
    box-shadow: 0 6px 15px rgba(0, 0, 0, 0.3);
}

/* 第三方登录：图标圆形及动态缩放 */
.login-thirdplatform {
    margin-top: 25px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.gitee-login {
    width: 45px;
    height: 45px;
    cursor: pointer;
    border-radius: 50%;
    transition: transform 0.3s;
    filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.3));
}
.gitee-login:hover {
    transform: scale(1.1);
}
/* 新增对话框层级保证 */
.el-dialog__wrapper {
  z-index: 9999 !important;
}
</style>
